package com.boxing;

import com.boxing.utils.Contants;
import com.boxing.utils.Utils;

import javax.naming.Name;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName="loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter init 执行了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter doFilter 执行了");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();
        System.out.println("当前访问的资源地址"+servletPath);
        System.out.println("login " + this+"   req:"+ request+"   session:" + request.getSession(true));
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login") || requestURI.contains("register")){
            filterChain.doFilter(request, response);
            return;
        }
        // 如果访问的是/webDemo/sub/login.html， 那么就不检验登录了
        if ("/sub/login.html".equals(servletPath) || "/sub/register.html".equals(servletPath)){
            filterChain.doFilter(request, response);
            return;
        }
        //校验token
        //获取到浏览器端传过来的token
        String token = Utils.getToken(request);
        // 第一种方式  获取当时生成的token
//        ServletContext servletContext = request.getServletContext();
//        // 创建token 跟浏览器传过来的token 比较
//        String initParameter = (String) servletContext.getAttribute(token);

        // 第二种方式 从session中获取token
        HttpSession session = request.getSession(true);
        String initParameter = (String) session.getAttribute(token);
        if (initParameter != null && initParameter.length()>0){
            // 已经登录过
            filterChain.doFilter(request, response);
        }else {
            // 没有登录， 跳转到登陆页面
            response.sendRedirect("/webDemo/sub/login.html");
        }
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter destroy 执行了");
    }
}
